package com.syezon.wifikey.ad;

import android.Manifest;
import android.app.Activity;
import android.util.Log;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.Utils;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTRewardVideoAd;
import com.hodanet.appadvplatclient.ReportAgent;
import com.hodanet.appadvplatclient.ad.AdInfo;
import com.qq.e.ads.rewardvideo.RewardVideoAD;
import com.qq.e.ads.rewardvideo.RewardVideoADListener;
import com.qq.e.comm.util.AdError;
import com.syezon.wifikey.channel.ChannelConfig;
import com.syezon.wifikey.config.GDTConfig;
import com.syezon.wifikey.config.TTAdManagerHolder;

import java.util.ArrayList;
import java.util.List;

public class VideoAd implements CommonAdCallBack {

    private static final String TAG_LOG = "video_ad";

    private Activity activity;
    private List<String> mVideoAdOrderList = new ArrayList<>();
    private TTAdNative mTTAdNative = TTAdManagerHolder.get().createAdNative(Utils.getApp());
    private TTRewardVideoAd mttRewardVideoAd;
    private RewardVideoAD mGDTRewardVideoAD;
    private OnVideoAdLoadFailedListener onVideoAdLoadFailedListener;

    public void setOnVideoAdLoadFailedListener(OnVideoAdLoadFailedListener onVideoAdLoadFailedListener) {
        this.onVideoAdLoadFailedListener = onVideoAdLoadFailedListener;
    }

    public interface OnVideoAdLoadFailedListener {
        void onVideoAdLoadFailed();
    }


    private int retryCount;

    public VideoAd(Activity activity) {
        this.activity = activity;
    }

    public void loadVideoAd() {
        String videoAdSource = OptVideoAdConfig.getVideoAdSource();
        mVideoAdOrderList = OptVideoAdConfig.getVideoAdOrderList();
        boolean permission = PermissionUtils.isGranted(Manifest.permission.READ_PHONE_STATE);
        loadVideoAd(videoAdSource);
    }

    public void loadVideoAd(AdInfo adInfo) {
        mVideoAdOrderList = OptVideoAdConfig.getVideoAdOrderList();
        if (adInfo.getType() == AdInfo.AD_TYPE_CHUAN_SHAN_JIA) {
            loadCsjVideoAd(adInfo);
        } else if (adInfo.getType() == AdInfo.AD_TYPE_GUANG_DIAN_TONG) {
            loadGdtVideoAd(adInfo);
        }
    }

    private void loadVideoAd(String adSource) {
        if (OptVideoAdConfig.VIDEO_AD_SOURCE_TT.equals(adSource)) {
            loadCsjVideoAd();
        } else if (OptVideoAdConfig.VIDEO_AD_SOURCE_GDT.equals(adSource)) {
            loadGdtVideoAd();
        }
    }

    private void loadGdtVideoAd() {
        loadGdtVideoAd(GDTConfig.VIDEO_ID);
    }

    private void loadGdtVideoAd(final String codeId) {
        try {
            mGDTRewardVideoAD = new RewardVideoAD(Utils.getApp(), GDTConfig.APP_ID, codeId, new RewardVideoADListener() {

                boolean reportShow;

                @Override
                public void onADLoad() {
                    onLoadSuccess(OptVideoAdConfig.VIDEO_AD_SOURCE_GDT);
                    mGDTRewardVideoAD.showAD();
                }

                @Override
                public void onVideoCached() {
                    LogUtils.eTag(TAG_LOG, "onVideoCached");
                }

                @Override
                public void onADShow() {
                    LogUtils.eTag(TAG_LOG, "onADShow");
                    if (!reportShow) {
                        reportShow = true;
                        SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_GDT, codeId, SDKReportHelper.OP_TYPE_SHOW);
                    }
                }

                @Override
                public void onADExpose() {
                    LogUtils.eTag(TAG_LOG, "onADExpose");
                }

                @Override
                public void onReward() {
                    LogUtils.eTag(TAG_LOG, "onReward");
                }

                @Override
                public void onADClick() {
                    LogUtils.eTag(TAG_LOG, "onADClick");
                    SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_GDT, codeId, SDKReportHelper.OP_TYPE_CLICK);
                }

                @Override
                public void onVideoComplete() {
                    LogUtils.eTag(TAG_LOG, "onVideoComplete");
                }

                @Override
                public void onADClose() {
                    LogUtils.eTag(TAG_LOG, "onADClose");
                }

                @Override
                public void onError(AdError adError) {
                    LogUtils.eTag(TAG_LOG, "onError " + adError.getErrorMsg());
                    onLoadFail(OptVideoAdConfig.VIDEO_AD_SOURCE_GDT, adError.getErrorMsg());
                    SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_GDT, codeId, SDKReportHelper.OP_TYPE_FAIL);
                }
            });
            mGDTRewardVideoAD.loadAD();
        } catch (Exception ignored) {

        }
    }


    private void loadCsjVideoAd() {
        loadCsjVideoAd(TTAdManagerHolder.VIDEO_AD);
    }


    public void loadCsjVideoAd(final String codeId) {
        try {
            //step4:创建广告请求参数AdSlot,具体参数含义参考文档
            AdSlot adSlot = new AdSlot.Builder()
                    .setCodeId(codeId)
                    .setSupportDeepLink(false)
                    .setImageAcceptedSize(1080, 1920)
                    .setRewardName("金币") //奖励的名称
                    .setRewardAmount(3)  //奖励的数量
                    .setUserID("user123")//用户id,必传参数
                    .setMediaExtra("media_extra") //附加参数，可选
                    .setOrientation(TTAdConstant.VERTICAL) //必填参数，期望视频的播放方向：TTAdConstant.HORIZONTAL 或 TTAdConstant.VERTICAL
                    .build();
            //step5:请求广告
            mTTAdNative.loadRewardVideoAd(adSlot, new TTAdNative.RewardVideoAdListener() {
                @Override
                public void onError(int code, String message) {
                    Log.e(TAG_LOG, message);
                    if(onVideoAdLoadFailedListener != null){
                        onVideoAdLoadFailedListener.onVideoAdLoadFailed();
                    }
//                    onLoadFail(OptVideoAdConfig.VIDEO_AD_SOURCE_TT, message);
                    SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_CSJ, codeId, SDKReportHelper.OP_TYPE_FAIL);
                }

                //视频广告加载后，视频资源缓存到本地的回调，在此回调后，播放本地视频，流畅不阻塞。
                @Override
                public void onRewardVideoCached() {
                    Log.e(TAG_LOG, "onRewardVideoCached");
//                TToast.show(RewardVideoActivity.this, "rewardVideoAd video cached");
                }

                //视频广告的素材加载完毕，比如视频url等，在此回调后，可以播放在线视频，网络不好可能出现加载缓冲，影响体验。
                @Override
                public void onRewardVideoAdLoad(TTRewardVideoAd ad) {
//                TToast.show(RewardVideoActivity.this, "rewardVideoAd loaded");
                    mttRewardVideoAd = ad;
                    onLoadSuccess(OptVideoAdConfig.VIDEO_AD_SOURCE_TT);
//                mttRewardVideoAd.setShowDownLoadBar(false);
                    mttRewardVideoAd.setRewardAdInteractionListener(new TTRewardVideoAd.RewardAdInteractionListener() {

                        boolean reportShow;

                        @Override
                        public void onAdShow() {
//                        TToast.show(RewardVideoActivity.this, "rewardVideoAd show");
                            if (!reportShow) {
                                SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_CSJ, codeId, SDKReportHelper.OP_TYPE_SHOW);
                                reportShow = true;
                            }
                        }

                        @Override
                        public void onAdVideoBarClick() {
//                        TToast.show(RewardVideoActivity.this, "rewardVideoAd bar click");
                            SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_CSJ, codeId, SDKReportHelper.OP_TYPE_CLICK);
                        }

                        @Override
                        public void onAdClose() {
//                        TToast.show(RewardVideoActivity.this, "rewardVideoAd close");
                        }

                        //视频播放完成回调
                        @Override
                        public void onVideoComplete() {
//                        TToast.show(RewardVideoActivity.this, "rewardVideoAd complete");
                        }

                        @Override
                        public void onVideoError() {
//                        TToast.show(RewardVideoActivity.this, "rewardVideoAd error");
                        }

                        //视频播放完成后，奖励验证回调，rewardVerify：是否有效，rewardAmount：奖励梳理，rewardName：奖励名称
                        @Override
                        public void onRewardVerify(boolean rewardVerify, int rewardAmount, String rewardName) {
//                        TToast.show(RewardVideoActivity.this, "verify:" + rewardVerify + " amount:" + rewardAmount +
//                                " name:" + rewardName);
                            Log.e(TAG_LOG, "onRewardVerify " + rewardVerify + rewardAmount + rewardName);
                        }

                        @Override
                        public void onSkippedVideo() {

                        }
                    });
                    mttRewardVideoAd.setDownloadListener(new TTAppDownloadListener() {

                        boolean reportDownload;
                        boolean reportInstall;

                        @Override
                        public void onIdle() {
//                        mHasShowDownloadActive = false;
                        }

                        @Override
                        public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
//                        if (!mHasShowDownloadActive) {
//                            mHasShowDownloadActive = true;
//                            TToast.show(RewardVideoActivity.this, "下载中，点击下载区域暂停", Toast.LENGTH_LONG);
//                        }
                        }

                        @Override
                        public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
//                        TToast.show(RewardVideoActivity.this, "下载暂停，点击下载区域继续", Toast.LENGTH_LONG);
                        }

                        @Override
                        public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
//                        TToast.show(RewardVideoActivity.this, "下载失败，点击下载区域重新下载", Toast.LENGTH_LONG);
                        }

                        @Override
                        public void onDownloadFinished(long totalBytes, String fileName, String appName) {
//                        TToast.show(RewardVideoActivity.this, "下载完成，点击下载区域重新下载", Toast.LENGTH_LONG);
                            if (!reportDownload) {
                                reportDownload = true;
                                SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_CSJ, codeId, SDKReportHelper.OP_TYPE_DOWNLOAD);
                            }
                        }

                        @Override
                        public void onInstalled(String fileName, String appName) {
//                        TToast.show(RewardVideoActivity.this, "安装完成，点击下载区域打开", Toast.LENGTH_LONG);
                            if (!reportInstall) {
                                reportInstall = true;
                                SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_CSJ, codeId, SDKReportHelper.OP_TYPE_INSTALL);
                            }
                        }
                    });
                    if (mttRewardVideoAd != null) {
                        mttRewardVideoAd.showRewardVideoAd(activity);
                    }
                }
            });
        } catch (Exception e) {

        }
    }
    private void loadGdtVideoAd(final AdInfo codeId) {
        try {
            mGDTRewardVideoAD = new RewardVideoAD(Utils.getApp(), GDTConfig.APP_ID, codeId.getCode(), new RewardVideoADListener() {

                boolean reportShow;

                @Override
                public void onADLoad() {
                    onLoadSuccess(OptVideoAdConfig.VIDEO_AD_SOURCE_GDT);
                    mGDTRewardVideoAD.showAD();
                }

                @Override
                public void onVideoCached() {
                    LogUtils.eTag(TAG_LOG, "onVideoCached");
                }

                @Override
                public void onADShow() {
                    LogUtils.eTag(TAG_LOG, "onADShow");
                    if (!reportShow) {
                        reportShow = true;
                        ReportAgent.reportAdvShow(codeId, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                    }
                }

                @Override
                public void onADExpose() {
                    LogUtils.eTag(TAG_LOG, "onADExpose");
                }

                @Override
                public void onReward() {
                    LogUtils.eTag(TAG_LOG, "onReward");
                }

                @Override
                public void onADClick() {
                    LogUtils.eTag(TAG_LOG, "onADClick");
                    ReportAgent.reportAdvSdkVideoClick(codeId, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                }

                @Override
                public void onVideoComplete() {
                    LogUtils.eTag(TAG_LOG, "onVideoComplete");
                }

                @Override
                public void onADClose() {
                    LogUtils.eTag(TAG_LOG, "onADClose");
                }

                @Override
                public void onError(AdError adError) {
                    LogUtils.eTag(TAG_LOG, "onError " + adError.getErrorMsg());
                    onLoadFail(OptVideoAdConfig.VIDEO_AD_SOURCE_GDT, adError.getErrorMsg());
                    ReportAgent.reportAdvSdkFailed(codeId, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                }
            });
            mGDTRewardVideoAD.loadAD();
        } catch (Exception ignored) {

        }
    }

    public void loadCsjVideoAd(final AdInfo codeId) {
        try {
            //step4:创建广告请求参数AdSlot,具体参数含义参考文档
            AdSlot adSlot = new AdSlot.Builder()
                    .setCodeId(codeId.getCode())
                    .setSupportDeepLink(false)
                    .setImageAcceptedSize(1080, 1920)
                    .setRewardName("金币") //奖励的名称
                    .setRewardAmount(3)  //奖励的数量
                    .setUserID("user123")//用户id,必传参数
                    .setMediaExtra("media_extra") //附加参数，可选
                    .setOrientation(TTAdConstant.VERTICAL) //必填参数，期望视频的播放方向：TTAdConstant.HORIZONTAL 或 TTAdConstant.VERTICAL
                    .build();
            //step5:请求广告
            mTTAdNative.loadRewardVideoAd(adSlot, new TTAdNative.RewardVideoAdListener() {
                @Override
                public void onError(int code, String message) {
                    Log.e(TAG_LOG, message);
                    if(onVideoAdLoadFailedListener != null){
                        onVideoAdLoadFailedListener.onVideoAdLoadFailed();
                    }
//                    onLoadFail(OptVideoAdConfig.VIDEO_AD_SOURCE_TT, message);
                    ReportAgent.reportAdvSdkFailed(codeId, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                }

                //视频广告加载后，视频资源缓存到本地的回调，在此回调后，播放本地视频，流畅不阻塞。
                @Override
                public void onRewardVideoCached() {
                    Log.e(TAG_LOG, "onRewardVideoCached");
//                TToast.show(RewardVideoActivity.this, "rewardVideoAd video cached");
                }

                //视频广告的素材加载完毕，比如视频url等，在此回调后，可以播放在线视频，网络不好可能出现加载缓冲，影响体验。
                @Override
                public void onRewardVideoAdLoad(TTRewardVideoAd ad) {
//                TToast.show(RewardVideoActivity.this, "rewardVideoAd loaded");
                    mttRewardVideoAd = ad;
                    onLoadSuccess(OptVideoAdConfig.VIDEO_AD_SOURCE_TT);
//                mttRewardVideoAd.setShowDownLoadBar(false);
                    mttRewardVideoAd.setRewardAdInteractionListener(new TTRewardVideoAd.RewardAdInteractionListener() {

                        boolean reportShow;

                        @Override
                        public void onAdShow() {
//                        TToast.show(RewardVideoActivity.this, "rewardVideoAd show");
                            if (!reportShow) {
                                ReportAgent.reportAdvShow(codeId, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                                reportShow = true;
                            }
                        }

                        @Override
                        public void onAdVideoBarClick() {
//                        TToast.show(RewardVideoActivity.this, "rewardVideoAd bar click");
                            ReportAgent.reportAdvSdkVideoClick(codeId, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                        }

                        @Override
                        public void onAdClose() {
//                        TToast.show(RewardVideoActivity.this, "rewardVideoAd close");
                        }

                        //视频播放完成回调
                        @Override
                        public void onVideoComplete() {
//                        TToast.show(RewardVideoActivity.this, "rewardVideoAd complete");
                        }

                        @Override
                        public void onVideoError() {
//                        TToast.show(RewardVideoActivity.this, "rewardVideoAd error");
                        }

                        //视频播放完成后，奖励验证回调，rewardVerify：是否有效，rewardAmount：奖励梳理，rewardName：奖励名称
                        @Override
                        public void onRewardVerify(boolean rewardVerify, int rewardAmount, String rewardName) {
//                        TToast.show(RewardVideoActivity.this, "verify:" + rewardVerify + " amount:" + rewardAmount +
//                                " name:" + rewardName);
                            Log.e(TAG_LOG, "onRewardVerify " + rewardVerify + rewardAmount + rewardName);
                        }

                        @Override
                        public void onSkippedVideo() {

                        }
                    });
                    mttRewardVideoAd.setDownloadListener(new TTAppDownloadListener() {

                        boolean reportDownload;
                        boolean reportInstall;

                        @Override
                        public void onIdle() {
//                        mHasShowDownloadActive = false;
                        }

                        @Override
                        public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
//                        if (!mHasShowDownloadActive) {
//                            mHasShowDownloadActive = true;
//                            TToast.show(RewardVideoActivity.this, "下载中，点击下载区域暂停", Toast.LENGTH_LONG);
//                        }
                        }

                        @Override
                        public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
//                        TToast.show(RewardVideoActivity.this, "下载暂停，点击下载区域继续", Toast.LENGTH_LONG);
                        }

                        @Override
                        public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
//                        TToast.show(RewardVideoActivity.this, "下载失败，点击下载区域重新下载", Toast.LENGTH_LONG);
                        }

                        @Override
                        public void onDownloadFinished(long totalBytes, String fileName, String appName) {
//                        TToast.show(RewardVideoActivity.this, "下载完成，点击下载区域重新下载", Toast.LENGTH_LONG);
                            if (!reportDownload) {
                                reportDownload = true;
                                ReportAgent.reportAdvDownload(codeId, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                            }
                        }

                        @Override
                        public void onInstalled(String fileName, String appName) {
//                        TToast.show(RewardVideoActivity.this, "安装完成，点击下载区域打开", Toast.LENGTH_LONG);
                            if (!reportInstall) {
                                reportInstall = true;
                                ReportAgent.reportAdvInstall(codeId, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                            }
                        }
                    });
                    if (mttRewardVideoAd != null) {
                        mttRewardVideoAd.showRewardVideoAd(activity);
                    }
                }
            });
        } catch (Exception e) {

        }
    }



    @Override
    public void onLoadSuccess(String adSourceCode) {
        LogUtils.eTag(TAG_LOG, "onLoadSuccess " + adSourceCode);
        OptVideoAdConfig.saveLastVideoAdCode(adSourceCode);
    }

    @Override
    public void onLoadFail(String adSourceCode, String errorMsg) {
        LogUtils.eTag("splash", "onLoadFail " + adSourceCode + " errorMsg " + errorMsg);
        String nextVideoAdCode = OptVideoAdConfig.getNextVideoAdCode(adSourceCode, mVideoAdOrderList, ++retryCount);
        loadVideoAd(nextVideoAdCode);
    }
}
